<template>
	<view class="flex-r wrap p16">
		<view class="goodbox" v-for="(item, index) of localList" :key="index" @tap="handClick(item.tCommodityid)">
			<image :src="getImgUrl(item.tCommodityimg)" class="goodimg" @error="imgerror($event, index)"></image>
			<view class="ellipsis pt10 fs13 gray">{{ item.tCommodityname }}</view>
			<view class="fs13 mt10" style="color: #999">距离{{ item.distance }}km</view>
		</view>
	</view>
</template>

<script>
import { ImgIP } from '@/utils/comm.js'
export default {
	name: 'shopList',
	props: {
		list: {
			type: Array,
			default() {
				return []
			}
		}
	},
	data() {
		return {
			u_long: '',
			u_lat: '',
			localList: [] // 定义本地的列表数据
		}
	},
	watch: {
		// 监听 prop 的变化，并同步到 localList
		list: {
			immediate: true,
			deep: true,
			handler(newList) {
				this.localList = newList.map((item) => ({
					...item,
					distance: '计算中。' // 初始化距离为 null
				}))
			}
		}
	},
	onReady() {
		this.getAuthorize()
			.then(() => {
				this.getLocationInfo()
			})
			.catch(() => {
				this.openConfirm()
					.then(() => {
						this.getLocationInfo()
					})
					.catch(() => {
						this.rejectGetLocation()
					})
			})
	},
	methods: {
		getAuthorize() {
			return new Promise((resolve, reject) => {
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						resolve() // 允许授权
					},
					fail: () => {
						reject() // 拒绝授权
					}
				})
			})
		},
		async getLocationInfo() {
			const that = this
			uni.getLocation({
				type: 'gcj02',
				success: function (res) {
					that.u_long = parseFloat(res.longitude.toFixed(6))
					that.u_lat = parseFloat(res.latitude.toFixed(6))
					that.updateListWithDistance() // 更新商品列表，计算距离
				}
			})
		},
		openConfirm() {
			return new Promise((resolve, reject) => {
				uni.showModal({
					title: '请求授权当前位置',
					content: '我们需要获取地理位置信息，为您推荐附近的商品',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting().then((res) => {
								if (res[1].authSetting['scope.userLocation'] === true) {
									resolve()
								} else {
									reject()
								}
							})
						} else if (res.cancel) {
							reject()
						}
					}
				})
			})
		},
		rejectGetLocation() {
			Utils.toast('你拒绝了授权，无法定位当前位置')
		},
		updateListWithDistance() {
			// 为每个商品计算距离并更新本地列表
			this.localList = this.localList.map((item) => {
				item.distance = this.getMapDistance(this.u_lat, this.u_long, item.tLatitude, item.tLongitude)
				return item
			})
		},
		Rad(d) {
			return (d * Math.PI) / 180.0
		},
		getMapDistance(lat1, lng1, lat2, lng2) {
			var radLat1 = this.Rad(lat1)
			var radLat2 = this.Rad(lat2)
			var a = radLat1 - radLat2
			var b = this.Rad(lng1) - this.Rad(lng2)
			var s =
				2 *
				Math.asin(
					Math.sqrt(
						Math.pow(Math.sin(a / 2), 2) +
							Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
					)
				)
			s = s * 6378.137 // 地球半径，单位为公里
			return Math.round(s * 100) / 100 // 保留两位小数
		},
		getImgUrl(image) {
			if (image == null) {
				return 'https://www.helloimg.com/i/2024/09/06/66dac3200f428.png'
			} else {
				let imageArr = image.split(',')
				let images = imageArr[0]
				return ImgIP + images
			}
		},
		handClick(tCommodityid) {
			uni.navigateTo({
				url: `/pages_C/goodDetail/goodDetail?tCommodityid=${tCommodityid}`
			})
		},
		imgerror(e) {
			console.log(e)
		}
	}
}
</script>

<style lang="stylus" scoped>
.gray2
	color #aaa
	font-size 24rpx
.goodbox
	width 50%
	box-sizing border-box
	padding 10rpx
.goodimg
	width 320rpx
	background #eee
	height 320rpx
.ellipsis
	-webkit-line-clamp 2
	display -webkit-box
	-webkit-box-orient vertical
	overflow hidden
	text-overflow ellipsis
</style>
